<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\validate;

use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate {

    /**
     * 验证参数
     * @return bool
     * @throws ParameterException
     */
    public function goCheck()
    {
        // 获取http传入的参数
        $request = Request::instance();
        $params = $request->param();
        
        // 对这些单数做校验
        $result = $this->batch()->check($params);
        if(!$result)
        {
            $e = new ParameterException(array(
                'msg' => $this->error,
            ));

            throw $e;
        }
        else
        {
            return true;
        }
    }

    /**
     * 参数是正整数
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool
     */
    protected function isPositiveInteger($value, $rule='', $data='', $field='')
    {
        if(is_numeric($value) && is_int($value + 0) && ($value + 0) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 验证手机号
     * @param $value
     * @return bool
     */
    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if($result)
        {
            return true;
        }
        return false;
    }

    /**
     * 参数不允许为空
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool
     */
    protected function isNotEmpty($value, $rule='', $data='', $field='')
    {
        if(empty($value))
        {
            return $field . '不允许为空';
        }
        else
        {
            return true;
        }
    }

    /**
     * 根据规则获取参数值
     * @param $arrays
     * @return array
     * @throws ParameterException
     */
    public function getDataByRule($arrays)
    {
        if(array_key_exists('user_id', $arrays) || array_key_exists('uid', $arrays))
        {
            throw new ParameterException([
                'msg' => '参数中包含有非法的参数名user_id或者uid'
            ]);
        }

        $newArray = [];

        foreach($this->rule as $key=>$value)
        {
            $newArray[$key] = $arrays[$key];
        }

        return $newArray;
    }
}